package logic

import (
	"context"
	"github.com/pkg/errors"
	"golang.org/x/crypto/bcrypt"
	"mall/app/member/model"
	"time"

	"mall/app/member/cmd/rpc/internal/svc"
	"mall/app/member/cmd/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Register 注册
func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {
	// 检查是否已经注册过
	ok, err := l.checkPhone(in.Phone)
	if err != nil {
		l.Errorf("l.checkPhone err: %+v", err)
		return nil, err
	}
	if !ok {
		// 手机合法
		return nil, errors.New("手机号已存在")
	}
	fromPassword, _ := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.MinCost)
	_, err = l.svcCtx.MemberModel.Insert(l.ctx, &model.UmsMember{
		Id:          1,
		LevelId:     0,
		Username:    in.UserName,
		Password:    string(fromPassword),
		Nickname:    "",
		Mobile:      in.Phone,
		Email:       "",
		Header:      "",
		Gender:      0,
		Birth:       time.Now(),
		City:        "",
		Job:         "",
		Sign:        "",
		SourceType:  0,
		Integration: 0,
		Growth:      0,
		Status:      1,
		CreateTime:  time.Now(),
	})
	if err != nil {
		l.Errorf("l.svcCtx.MemberModel.Insert err: %+v", err)
		return nil, errors.New("MemberModel.Insert err")
	}
	return &pb.RegisterResp{}, nil
}

func (l *RegisterLogic) checkPhone(phone string) (bool, error) {
	cnt, err := l.svcCtx.MemberModel.GetCountByPhone(l.ctx, phone)
	if err != nil {
		return false, err
	}
	if cnt == 0 {
		// 不存在该手机号用户
		return true, nil
	} else {
		// 已经存在
		return false, nil
	}
}
